package com.yyge.controller.admin.employee;

import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yyge.common.controller.BaseController;
import com.yyge.common.enums.AckCode;
import com.yyge.common.util.WaimaiThreadLocal;
import com.yyge.common.vo.req.PageReq;
import com.yyge.common.vo.resp.PageResp;
import com.yyge.controller.admin.employee.req.EmployeeReq;
import com.yyge.controller.admin.employee.resp.EmployeeResp;
import com.yyge.controller.admin.mapstruct.EmployeeConverter;
import com.yyge.entity.Employee;
import com.yyge.service.EmployeeService;
import com.yyge.common.vo.resp.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.crypto.spec.PSource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/api/employee")
public class EmployeeController extends BaseController<Employee,Object> {
    public EmployeeController() {
        this.converter=EmployeeConverter.class;
    }
    // 注入业务逻辑层
    private EmployeeService service;

    @Autowired/*自动装配*/
    public void setService(EmployeeService employeeService){
        this.service=employeeService;
    }

    @GetMapping("data")/* GET(SELECT): 查询 */
    public R<PageResp<EmployeeResp>> get(EmployeeReq req) throws Exception  {
         // 将对象进行转换过滤无效条件
        QueryWrapper queryWrapper = this.getWrapper(req);
        PageResp<EmployeeResp> pageResp =this.page(req,pageInfo ->service.page(pageInfo,queryWrapper));
        System.out.println("检查pageResp是不是返回EmployeeResp");
        System.out.println(pageResp.getRows());
        return R.okHasData(pageResp);
    }

    @GetMapping("{id}")/* GET(SELECT): 查询 */
    public R getByID(PageReq<Employee> vo,EmployeeReq req) throws Exception  {

        QueryWrapper<Employee> warpper = getWrapper(req);
        warpper.eq("id",req.getId());
        PageResp pageResp =this.page(req,pageInfo ->service.page(pageInfo,warpper));
        List rows = pageResp.getRows();

        System.out.println("-------------------测试");
        System.out.println(pageResp);
        return R.okHasData(rows.get(0));
    }

    @PostMapping/* POST(CREATE): 修改 */
    public R post(@RequestBody EmployeeReq req){
        // 将对象进行转换过滤无效条件
        Employee employee = EmployeeConverter.MAPPER.convert(req);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        //获取当前用户
        employee.setCreateBy(WaimaiThreadLocal.getName());
        employee.setUpdateBy(WaimaiThreadLocal.getName());

        //密码加密

        //密码加密
        String pwd= BCrypt.hashpw(employee.getLoginPwd());
        employee.setLoginPwd(pwd);

        Boolean i=service.save(employee);
        return i?R.ok("新增成功！"):R.error(AckCode.SYSTEM_SERVICE_ADD_ERROR);
    }


    @PutMapping/* POST(CREATE): 修改 */
    public R out(@RequestBody EmployeeReq req){
        if( req.getId().intValue()<=0){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        //将对象进行转换过滤无效条件
        Employee  employee= EmployeeConverter.MAPPER.convert(req);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        //获取当前用户
        employee.setCreateBy(WaimaiThreadLocal.getName());
        employee.setUpdateBy(WaimaiThreadLocal.getName());

        //密码加密
        String pwd= BCrypt.hashpw(employee.getLoginPwd());
        employee.setLoginPwd(pwd);

        Boolean i=service.updateById(employee);
        return i?R.ok("修改成功！"):R.error(AckCode.SYSTEM_SERVICE_MODIFY_ERROR);
    }

    @PatchMapping/* PUT(UPDATE): 部分更新 */
    public R patch(@RequestBody Employee employee){
        return null;
    }

    @ApiOperation(value = "逻辑删除")
    @DeleteMapping/* DELETE(DELETE): 删除&&批量删除 */
    public R delete(Long[] ids){
       if(Objects.isNull(ids) || ids.length==0){
           return R.build(AckCode.SYSTEM_PARAM_FAIL);
       }

        Employee employee=new Employee();
        employee.setStatus("1");
        employee.setUpdateTime(new Date());
        employee.setUpdateBy(WaimaiThreadLocal.getName());

        List<Long> longs = Arrays.asList(ids);
        //超级管理员的ID=1不允许禁用的
        longs.remove(1L);

        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Employee::getId, ids);
        boolean batchById = service.update(employee,queryWrapper);

        return batchById?R.ok("修改成功！"):R.error(AckCode.SYSTEM_SERVICE_DELETE_ERROR);
    }

    @ApiOperation(value = "excel下载")
    @PostMapping(value = "/download")
    public void download(HttpServletResponse response, @RequestBody EmployeeReq req) throws Exception {
        QueryWrapper selectWrapper=this.getWrapper(req);
        List<Employee> arrList=this.service.list(selectWrapper);
        List<EmployeeResp> convert = EmployeeConverter.MAPPER.convert(arrList);;

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("data", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), EmployeeResp.class).sheet("数据").doWrite(convert);
    }
}

